package cn.icanci.ladybird.service.util.impl;

import cn.icanci.ladybird.pojo.dto.UserClassDetailsDto;
import cn.icanci.ladybird.service.TicketDetailsService;
import cn.icanci.ladybird.service.util.ElasticSearchService;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: icanci
 * @date: Created in 2020/10/20 10:27
 * @classAction: 操作搜索引擎的service
 */
@Service
@SuppressWarnings("all")
public class ElasticSearchServiceImpl implements ElasticSearchService {
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;
    @Autowired
    private TicketDetailsService ticketDetailsService;

    @Override
    public boolean parseContent() throws Exception {
        // 查询数据库所有的数据
        List<UserClassDetailsDto> userClassDetailsDtos = ticketDetailsService.queryTicketDetailsAll();
        if (null == userClassDetailsDtos && userClassDetailsDtos.size() == 0) {
            return false;
        }
        // 先删除索引
        DeleteIndexRequest request = new DeleteIndexRequest("ladybird_boot_index");
        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        // 在增加
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for (UserClassDetailsDto detailsDto : userClassDetailsDtos) {
            bulkRequest.add(new IndexRequest("ladybird_boot_index")
                    .source(JSON
                            .toJSONString(detailsDto), XContentType.JSON));
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }

    @Override
    public List<Map<String, Object>> searchPage(String keyword, int pageNo, int pageSize) throws Exception {
        if (pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize < 1) {
            pageSize = 20;
        }
        // 条件搜索
        SearchRequest searchRequest = new SearchRequest("ladybird_boot_index");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 分页实现
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);
        // 精准匹配
        TermQueryBuilder ticketDetailsInfo = QueryBuilders.termQuery("ticketDetailsInfo", keyword);
        sourceBuilder.query(ticketDetailsInfo);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        // 执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        // 解析结果
        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            maps.add(hit.getSourceAsMap());
        }
        return maps;
    }

    @Override
    public List<Map<String, Object>> searchPageHigh(String keyword, int pageNo, int pageSize) throws Exception {
        System.out.println(keyword);
        if (pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize < 1) {
            pageSize = 20;
        }
        // 条件搜索
        SearchRequest searchRequest = new SearchRequest("ladybird_boot_index");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 分页实现
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);
        // QueryBuilders.termQuery  精确匹配
        // QueryBuilders.matchAllQuery() 匹配所有
        TermQueryBuilder ticketDetailsInfo = QueryBuilders.termQuery("ticketDetailsInfo", keyword);
        sourceBuilder.query(ticketDetailsInfo);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        // 高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("ticketDetailsInfo");
        // 多个高亮一个
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);
        // 执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        // 解析结果
        ArrayList<Map<String, Object>> maps = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            // 解析高亮的字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField ticketDetailsInfo1 = highlightFields.get("ticketDetailsInfo");
            // 原来的结果
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //
            if (ticketDetailsInfo1 != null) {
                Text[] fragments = ticketDetailsInfo1.fragments();
                String new_ticketDetailsInfo1 = "";
                for (Text fragment : fragments) {
                    new_ticketDetailsInfo1 += fragment;
                }
                // 替换原来的内容
                sourceAsMap.put("ticketDetailsInfo", new_ticketDetailsInfo1);
            }
            maps.add(sourceAsMap);
        }
        return maps;
    }
}
